package cn.liutao.order.api;

import cn.liutao.common.entity.LoginUser;
import cn.liutao.common.entity.Validation;
import cn.liutao.common.enums.OrderEnum;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.common.utils.ValidUtil;
import cn.liutao.order.entity.po.Cart;
import cn.liutao.order.entity.vo.CartVo;
import cn.liutao.order.service.CartService;
import com.mybatisflex.core.paginate.Page;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author liutao
 * @Description 购物车api
 * @date 2023/11/1 16:46
 * @Version 1.0
 */
@WebServlet("/cart")
@Slf4j
public class CartServlet extends HttpServlet {
    private CartService cartService;

    @Override
    public void init() throws ServletException {
        cartService = CartService.getInstance();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp){
        Cart queryParam = ServletUtils.getQueryParam(req, Cart.class);
        if (queryParam.getStatus()==null) queryParam.setStatus(OrderEnum.CART_STATUS_NO_BUY.getIntValue());
        if (queryParam.getType()==null) queryParam.setStatus(OrderEnum.CART_TYPE_ADD_CART.getIntValue());
        Integer userId = LoginUser.getUserId();
        queryParam.setUserId(userId);
        Page<CartVo> page = cartService.selectByList(queryParam);
        ServletUtils.ok(resp,page);
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        Cart addParam = ServletUtils.getBodyParam(req, Cart.class);
        ValidUtil.validated(addParam, Validation.AddGroup.class);
        Integer userId = LoginUser.getUserId();
        addParam.setUserId(userId);
        cartService.insert(addParam);
        ServletUtils.ok(resp,"新增成功");
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp){
        Cart editParam = ServletUtils.getBodyParam(req, Cart.class);
        ValidUtil.validated(editParam,Validation.EditGroup.class);
        Integer userId = LoginUser.getUserId();
        editParam.setUserId(userId);
        cartService.updateById(editParam);
        ServletUtils.ok(resp,"修改成功");
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp){
        List<String> ids = ServletUtils.getQueryParams(req, "id");
        for (String id : ids) {
            cartService.removeById(Integer.valueOf(id));
        }
        ServletUtils.ok(resp,"删除成功");
    }

}
